#include "publish_image.h"
#include <zmq.hpp>
#include <iostream>
#include <chrono>
#include <thread>
#include <vector>
#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>  
#include <opencv2/highgui/highgui.hpp>
using namespace cv;


int PublishImage::startPublish(const std::string& video_url)
{
    zmq::context_t context(1);
    zmq::socket_t publisher(context, ZMQ_PUB);
    std::string addr = "ipc:///tmp/tmp_zmq.ipc";
    publisher.bind(addr);

    cv::Mat frame;
    cv::VideoCapture cap;
    bool isopend = cap.open(video_url);
    if (!isopend)
    {
        std::cout << "open video failed!" << std::endl;
        return -1;
    }

    while (cap.isOpened() && !_needStop)
    {
        cap >> frame;
        //std::cout << frame.cols << " " << frame.rows << std::endl;

        int width = frame.cols;
        int height = frame.rows;
        int channel = frame.channels();
        uint32_t img_size = frame.total()*frame.elemSize();

        std::string zmq_data;
        zmq_data.resize(12 + img_size);
        memcpy((char*)zmq_data.data(), (char*)&width, 4);
        memcpy((char*)zmq_data.data() + 4, (char*)&height, 4);
        memcpy((char*)zmq_data.data() + 8, (char*)&channel, 4);
        memcpy((char*)zmq_data.data() + 12, (char*)frame.data, img_size);

        zmq::message_t msg(zmq_data.size());
        memcpy(msg.data(), zmq_data.data(), zmq_data.size());
        publisher.send(msg);
        // std::this_thread::sleep_for(std::chrono::seconds(1));
    }
    _needStop = false;
    _stopped = true;
    cap.release();
    return 0;
}


void PublishImage::stopPublish()
{
    _needStop = true;
}